import Vue from 'vue'
import VueRouter from 'vue-router'
import Reg from '@/views/Reg/Reg.vue'
import Login from '@/views/Login/Login.vue'
import Main from '@/views/Main/Main.vue'
import Home from '@/views/Menus/Home.vue'
import Userinfo from '@/views/Menus/User/Userinfo.vue'
import UserAvatar from '@/views/Menus/User/UserAvatar.vue'
import UserPwd from '@/views/Menus/User/UserPwd.vue'
import ArtCate from '@/views/Menus/Article/ArtCate.vue'
import ArtList from '@/views/Menus/Article/ArtList.vue'
import store from '@/store'

Vue.use(VueRouter)

const routes = [
  // 每一条对象都是路由规则
  { path: '/reg', component: Reg },
  { path: '/login', component: Login },
  {
    path: '/',
    component: Main,
    redirect: '/home',
    children: [
      // 二级路由默认不加 /   加 / 它会拼接父路由
      { path: 'home', component: Home },
      { path: 'user-info', component: Userinfo },
      { path: 'user-avatar', component: UserAvatar },
      { path: 'user-pwd', component: UserPwd },
      { path: 'art-cate', component: ArtCate },
      { path: 'art-list', component: ArtList }
    ]
  }
]

const router = new VueRouter({
  routes
})

// 添加全局前置守卫
// to 到哪里去
// from 从哪里来
// next 是否放行
//  next() 放行
//  next(false) 不放行
//  next('路径') 强制跳转
router.beforeEach((to, from, next) => {
  // 需求: 如果没有登录不允许去首页,但允许去登录页 / 注册页
//  登录的判断依据:是否有 token
  const token = store.state.user.token
  // console.log(to, from)
  // if (to.path === '/login') {
  //   return next()
  // }
  const whiteList = ['/login', '/reg'] // 白名单
  if (!token && !whiteList.includes(to.path)) {
    next('/login')

    // 提醒用户未登录
    Vue.prototype.$message.error('你还未登录哟!')
  } else {
    next()
  }
})

export default router
